package com.ct.onlinemusic.controller;


import com.ct.onlinemusic.enums.ResultCode;
import com.ct.onlinemusic.model.MusicInfo;
import com.ct.onlinemusic.service.MusicService;
import com.ct.onlinemusic.tools.Constant;
import com.ct.onlinemusic.tools.ResponseMessage;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/music")
public class MusicController {
    @Autowired
    private MusicService musicService;

    @Value("${music.local.path}")
    private String SAVE_PATH;

    /**
     * 上传音乐
     * @param singer   歌手
     * @param file     音乐源文件
     * @param session  服务器记录登录信息
     * @return         上传信息
     */
    @RequestMapping("/upload")
    public ResponseMessage<Boolean> insertMusic (MultipartFile file, String singer,
                                                 HttpSession session, HttpServletResponse resp) throws IOException {
        log.info("上传音乐:{}", singer);
        if (session == null || session.getAttribute(Constant.USERINFO_SESSION_KEY) == null) {
            log.error("没有登录...");
            return new ResponseMessage<>(ResultCode.UNLOGIN.getCode(), "没有登录!", false);
        }
        if (file == null || file.isEmpty()) return new ResponseMessage<Boolean>(ResultCode.FAIL.getCode(), "没上传音乐", false);
        Integer result = musicService.isUpload(singer, file, session);
        if (result == 1) {
            resp.sendRedirect("/list.html");
            return new ResponseMessage<>(ResultCode.SUCCESS.getCode(), "上传成功", true);
        } else if (result == -1) {
            return new ResponseMessage<>(ResultCode.FAIL.getCode(), "上传失败", false);
        } else {
            return new ResponseMessage<>(ResultCode.FAIL.getCode(), "数据库上传失败, 删除上传的音乐", false);
        }
    }

    @RequestMapping("/get")
    public ResponseEntity<byte[]> get(String path) {
        File file = new File(SAVE_PATH+"/"+path);
        byte[] a = null;
        try {
            a = Files.readAllBytes(file.toPath());
            if(a == null) {
                return ResponseEntity.badRequest().build();
            }
            return ResponseEntity.ok(a);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.badRequest().build();
        //return ResponseEntity.internalServerError().build();
        //return ResponseEntity.notFound().build();
    }

    /**
     * 通过Id删除音乐
     * @param id 音乐Id
     * @return   删除信息
     */
    @RequestMapping("/delete")
    public ResponseMessage<Boolean> delete (Integer id) {
        log.info("删除音乐:{}", id);
        try {
            Integer result =  musicService.deleteById(id);
            if (result <= 0) {
                return new ResponseMessage<>(ResultCode.FAIL.getCode(), "删除音乐失败", false);
            } else {
                return new ResponseMessage<>(ResultCode.SUCCESS.getCode(), "删除音乐成功", true);
            }
        } catch (Exception e) {
            log.error("删除音乐异常:", e);
            return new ResponseMessage<>(ResultCode.FAIL.getCode(), e.getMessage(), false);
        }
    }

    /**
     * 删除所选音乐
     * @param ids 所要删除音乐的id
     * @return    返回的信息
     */
    @RequestMapping("/deleteSel")
    public ResponseMessage<Boolean> deleteSel (@RequestParam List<Integer> ids) {
        log.info("一键删除:{}", ids);
        try {
            Integer result = musicService.deleteSel(ids);
            if (result <=  0) {
                return new ResponseMessage<>(ResultCode.FAIL.getCode(), "删除音乐失败" , false);
            }
            return new ResponseMessage<>(ResultCode.SUCCESS.getCode(), "删除音乐成功", true);
        } catch (Exception e) {
            log.error("删除音乐异常:", e);
            return new ResponseMessage<>(ResultCode.FAIL.getCode(), e.getMessage(), false);
        }
    }

    /**
     * 模糊查询歌曲
     * @param title 歌曲名
     * @return      歌曲
     */
    @RequestMapping("/findMusicByTitle")
    public ResponseMessage<List<MusicInfo>> findMusicByTitle (String title) {
        log.info("查找音乐:{}", title);
        try {
            List<MusicInfo> result = musicService.findMusicByTitle(title);
            if (result == null || result.size() == 0) {
                return new ResponseMessage<>(ResultCode.FAIL.getCode(), "未找到歌曲", result);
            }
            return new ResponseMessage<>(ResultCode.SUCCESS.getCode(), "成功找到歌曲", result);
        } catch (Exception e) {
            log.error("发生异常e:", e);
            return new ResponseMessage<>(ResultCode.FAIL.getCode(), e.getMessage(), null);
        }
    }



}
